"""Input helper functions / key bindings."""

__author__ = 'Josh Oosterman'

import pygame.key
import pygame.mouse

from potv import geom


# Controls.
PLAYER_UP = EDITOR_UP = pygame.K_w
PLAYER_DOWN = EDITOR_DOWN = pygame.K_s
PLAYER_LEFT = EDITOR_LEFT = pygame.K_a
PLAYER_RIGHT = EDITOR_RIGHT = pygame.K_d
CAR_ACCELERATE = pygame.K_UP
CAR_DECELERATE = pygame.K_DOWN
CAR_STEER_LEFT = pygame.K_LEFT
CAR_STEER_RIGHT = pygame.K_RIGHT
EDITOR_SAVE = pygame.K_z

TOGGLE_DEBUG = pygame.K_F2
QUIT_GAME = pygame.K_ESCAPE

# TODO(joosterman): Tidy up.
_keys = {}
_last_keys = {}
_mouse = (0, 0, 0)
_last_mouse = (0, 0, 0)

def Update():
  """Update the current key state. Call once per frame."""
  global _keys, _last_keys, _mouse, _last_mouse
  _last_keys = _keys
  _last_mouse = _mouse
  _keys = pygame.key.get_pressed()
  _mouse = pygame.mouse.get_pressed()


def IsDown(key):
  """Returns whether a key is currently pressed."""
  global _keys
  return _keys[key]


def WasPressed(key):
  """Returns whether a key was pressed this frame."""
  global _keys, _last_keys
  return _keys[key] and not _last_keys[key]


def WasReleased(key):
  """Returns whether a key was released this frame."""
  global _keys, _last_keys
  return not _keys[key] and _last_keys[key]


def IsMouseDown(button=0):
  """Returns whether a mouse button is currently pressed."""
  global _mouse
  return _mouse[button]


def WasMousePressed(button=0):
  """Returns whether a mouse button was pressed this frame."""
  global _mouse, _last_mouse
  return _mouse[button] and not _last_mouse[button]


def WasMouseReleased(button=0):
  """Returns whether a mouse button was released this frame."""
  global _mouse, _last_mouse
  return not _mouse[button] and _last_mouse[button]


def GetMouseScreenPosition():
  """Returns the position of the mouse on the screen."""
  return geom.Vector(*pygame.mouse.get_pos())


def GetMouseWorldPosition(level):
  """Returns the world position of the mouse (including view offsets)."""
  position_absolute = GetMouseScreenPosition()
  for view in level.views:
    if position_absolute in view.rect:
      return view.world_location + position_absolute
  return geom.Vector(0, 0)
